package com.gitee.sop.gateway.request;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.gitee.sop.gateway.common.SopConstants;
import com.gitee.sop.gateway.config.ApiConfig;
import com.gitee.sop.gateway.util.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;

/**
 * @author 六如
 */
@Slf4j
public class ApiRequestContextFactory {

    private static final String CONTENT_TYPE = "content-type";
    private static final String JSON_NAME = "json";
    private static final String TEXT_NAME = "text";
    private static final String MULTIPART = "multipart";
    public static final String FORM = "form";

    public static ApiRequestContext build(HttpServletRequest request, ApiConfig apiConfig) {
        // get请求可能返回null
        String contentType = request.getHeader(CONTENT_TYPE);
        if (contentType == null) {
            contentType = "";
        }
        ApiRequest apiRequest = new ApiRequest();
        String ip = RequestUtil.getIP(request);
        byte[] body;
        try {
            body = IOUtils.toByteArray(request.getInputStream());
        } catch (IOException e) {
            log.error("获取请求体失败", e);
            body = new byte[0];
        }
        JSONObject params = null;
        UploadContext uploadContext = null;
        String contentTypeStr = contentType.toLowerCase();
        // 如果是json方式提交
        if (StringUtils.containsAny(contentTypeStr, JSON_NAME, TEXT_NAME)) {
            params = JSON.parseObject(body);
        } else if (StringUtils.containsIgnoreCase(contentTypeStr, MULTIPART)) {
            // 如果是文件上传请求
            RequestUtil.UploadInfo uploadInfo = RequestUtil.getUploadInfo(request);
            params = uploadInfo.getApiParam();
            uploadContext = uploadInfo.getUploadContext();
        } else if (StringUtils.containsIgnoreCase(contentTypeStr, FORM)) {
            // APPLICATION_FORM_URLENCODED请求
            params = RequestUtil.parseQuerystring(new String(body, SopConstants.CHARSET_UTF8));
        } else {
            // get请求,参数跟在url后面
            params = RequestUtil.parseParameterMap(request.getParameterMap());
        }
        if (params != null) {
            apiRequest = params.toJavaObject(ApiRequest.class);
        }

        return ApiRequestContext.builder()
                .apiRequest(apiRequest)
                .locale(request.getLocale())
                .ip(ip)
                .uploadContext(uploadContext)
                .traceId(UUID.randomUUID().toString().replace("-", ""))
                .build();
    }

}
